package com.ght.springboot.elasticsearch;

import ch.qos.logback.core.net.server.Client;
import com.ght.springboot.elasticsearch.domain.BaseMapping;
import com.ght.springboot.elasticsearch.domain.BlackAddressMapping;
import com.ght.springboot.elasticsearch.domain.FieldAttribute;
import com.ght.springboot.eunm.BulkMethodEnum;
import com.ght.springboot.util.ImportExcel;
import com.ght.springboot.util.MyEasyJsonUtil;
import com.ght.springboot.vo.BlackAddressVo;
import com.ght.springboot.vo.ZDoc;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.*;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.DeleteIndex;
import io.searchbox.indices.mapping.GetMapping;
import io.searchbox.indices.mapping.PutMapping;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @description: 索引相关操作
 * @author: haitao.gao
 * @create: 2019-01-29 10:29
 **/
public class IndexOperate {

    public JestClient jestClient;

    public IndexOperate(){
        if(jestClient == null){
            jestClient = EsJestClient.getClient();
        }
    }

    /**
     * 获取索引映射
     */
    public void getIndex(String index,String type){
        GetMapping.Builder builder = new GetMapping.Builder();
        builder.addIndex(index).addType(type);
        try {
            JestResult jestResult = jestClient.execute(builder.build());
            System.out.print(jestResult.getJsonObject());
        }catch (Exception e){
            System.out.print(e);
        }
    }

    /**
     * 删除索引
     * @param args
     */
    public void deleteIndex(String index){

        try {
            JestResult jestResult = jestClient.execute(new DeleteIndex.Builder(index).build() );
        }catch (Exception e){
        }
    }

    /**
     * 指定Mapping创建索引
     * @param args
     */
    public void createIndexBymapping(String index,String type,String mapping){

        // PUT http://ip:port/index/type/_mapping
        PutMapping putMapping = new PutMapping.Builder(index,type,mapping).build();
        try{
            JestResult jestResult = jestClient.execute(putMapping);
        }catch (Exception e){
            System.out.print(e);
        }

    }

    /**
     * 修改Mapping映射
     */
    public void updateIndexMapping(String index,String type,String mapping){

    }

    /**
     * 删除Type
     */
    public void deleteIndexMapping(String index,String type){
        DeleteIndex deleteIndex = new DeleteIndex.Builder(index).type(type).build();
        try{
            JestResult jestResult = jestClient.execute(deleteIndex);
            System.out.print(jestResult.getJsonObject().toString());
        }catch (Exception e){
            System.out.print(e);
        }
    }

    /**
     * 创建索引
     * @param args
     */
    public void createIndex(String indexName,String type){
        try {
            JestResult jestResult = jestClient.execute(new CreateIndex.Builder(indexName).build());
            System.out.print(jestResult.getJsonString());
        }catch (Exception e){
            System.out.print(e);
        }
    }

    /**
     * 插入数据
     * @param args
     */
    public void insert(String indexName,String typeName,String date){

        Index index = new Index.Builder(date).index(indexName).type(typeName).build();
        try {
            JestResult jestResult = jestClient.execute(index);
            System.out.print(jestResult.getJsonString());
        }catch (Exception e){
            System.out.print(e);
        }

    }

    /**
     *
     * @param indexName 索引
     * @param typeName  类型
     * @param OperateType 批量操作类型
     * @param id        文档ID
     * @param dateList   操作数据
     */
    public void bulk(String indexName,String typeName,String OperateType,String id,List<String> dateList){
        Bulk.Builder bulkBuilder = new Bulk.Builder().defaultIndex(indexName).defaultIndex(typeName);
        dateList.forEach(date->{
            if(OperateType.equals(BulkMethodEnum.INSERT.getType())){
                bulkBuilder.addAction(new Index.Builder(date).index(indexName).type(typeName).build());
            }
            else if(OperateType.equals(BulkMethodEnum.UPDATE.getType())){
                bulkBuilder.addAction(new Update.Builder(date).index(indexName).type(typeName).build());
            }
        });
        if(OperateType.equals(BulkMethodEnum.DELETE.getType())){
            bulkBuilder.addAction(new Delete.Builder(null).index(indexName).type(typeName).build());
        }
        try {
            JestResult jestResult = jestClient.execute(bulkBuilder.build());
            System.out.print("批量操作结果" + jestResult.getJsonString());
        }catch (Exception e){
            System.out.print("批量操作异常"+e);
        }
    }

    public void batchInsert(MultipartFile multipartFile) throws Exception {

        InputStream inputStream = multipartFile.getInputStream();
        ImportExcel importExcel = new ImportExcel();
        List<String> dateList = new ArrayList<>();
        List<BlackAddressVo> blackAddressVoList = importExcel.parseExcelToClass(inputStream,BlackAddressVo.class,1,0,0);
        blackAddressVoList.forEach(blackAddress->{
            dateList.add(MyEasyJsonUtil.json2string(blackAddress));
//            insert(DocumentDB.INDICES,"3:4",MyEasyJsonUtil.json2string(blackAddress));
        });
        bulk(DocumentDB.INDICES,"4:3","index",null,dateList);
    }

    /**
     * 单文档删除
     * @param indexName
     * @param typeName
     * @param id
     */
    public void deleteDoc(String indexName,String typeName,String id){
        Delete delete = new Delete.Builder(id).index(indexName).type(typeName).build();
        try{
            JestResult jestResult = jestClient.execute(delete);
            System.out.print(jestResult.getJsonString());
        }catch (Exception e){
            System.out.print(e);
        }
    }

    public void deleteByQuery(String indexName,String typeName,String queryJson){
        if(StringUtils.isBlank(queryJson)){
            queryJson = "{\"query\":{\"match_all\":{}}}";
        }
        DeleteByQuery deleteByQuery = new DeleteByQuery.Builder(queryJson).addIndex(indexName).addType(typeName).build();
        try{
            JestResult jestResult = jestClient.execute(deleteByQuery);
            System.out.print(jestResult.getJsonString());
        }catch (Exception e){
            System.out.print(e);
        }

    }

    /**
     *   简单批量化获取(可以指字段)
     * @param indexName
     * @param typeName 选填
     * @param ids
     */
    public void mget(List<ZDoc> zDocList){
//        ids.forEach(id->docList.add(StringUtils.isBlank(typeName)?new Doc(indexName,id):new Doc(indexName,typeName,id)));
        MultiGet multiGet = new MultiGet.Builder.ByDoc(zDocList).build();
        try{
            JestResult jestResult = jestClient.execute(multiGet);
            System.out.print(jestResult.getJsonString());
        }catch (Exception e){
            System.out.print(e);
        }
    }

    public static void main(String[] args) {
        IndexOperate indexOperate = new IndexOperate();
//        indexOperate.createIndex(DocumentDB.INDICES,"black_address");
//        indexOperate.deleteIndex(DocumentDB.INDICES);
        String mapping = "{\"properties\":{\"address\":{\"type\":\"string\",\"analyzer\":\"english\"},\"state\":{\"type\":\"string\",\"analyzer\":\"english\"},\"country\":{\"type\":\"string\",\"analyzer\":\"english\"},\"city\":{\"type\":\"string\",\"analyzer\":\"english\"}}}";
        String doc1 = "{\"address\":\"This is a test address for gaohaitao\",\"state\":\"US\",\"phone\":\"13678785656\"}";
        BlackAddressMapping blackAddressMapping = new BlackAddressMapping(new FieldAttribute("text","english",10)
                                                    ,new FieldAttribute("text","english",2)
                                                    ,new FieldAttribute("text","english",1)
                                                    ,new FieldAttribute("text","english",1)
                                                    ,new FieldAttribute("keyword",null,10));
        BaseMapping baseMapping = new BaseMapping(blackAddressMapping);

//        indexOperate.deleteIndexMapping(DocumentDB.INDICES,"black_address");
//        indexOperate.createIndexBymapping(DocumentDB.INDICES,"black_address",MyEasyJsonUtil.json2string(baseMapping));
//        indexOperate.getIndex(DocumentDB.INDICES,"black_address");
//        indexOperate.insert(DocumentDB.INDICES,"black_address",doc1);
//        indexOperate.bulk(DocumentDB.INDICES,"3:4","index",null,new ArrayList<>());
//        indexOperate.deleteDoc(DocumentDB.INDICES,"3:4");
//        indexOperate.deleteByQuery(DocumentDB.INDICES,"4:3",null);
        List<ZDoc> zDocList = new ArrayList<>();
        zDocList.add(new ZDoc("black_address","",Arrays.asList("AWiioP-v-ivLNmq_6SoUnianqina","")));
        indexOperate.mget(DocumentDB.INDICES,"4:3",ids);

    }

}
